package com.haozhen.demo1;


import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author haozhen
 * @email haozh@ync1.com
 * @date 2021/2/8  1:20
 */
public class WordCountJavaStream {


    public static void main(String[] args) {
        String inputPath = "data/input/hello.txt";
        String output = "data/output";

        StreamExecutionEnvironment executionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStream<String> ds1 = executionEnvironment.socketTextStream("localhost", 9999);

        SingleOutputStreamOperator<Tuple2<String, Integer>> tuple2SingleOutputStreamOperator = ds1.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String text, Collector<Tuple2<String, Integer>> collector) throws Exception {
                String[] s = text.split(" ");
                for (String s1 : s) {
                    Tuple2<String, Integer> stringIntegerTuple2 = new Tuple2<>(s1, 1);
                    collector.collect(stringIntegerTuple2);
                }
            }
        });

        SingleOutputStreamOperator<Tuple2<String, Integer>> sum = tuple2SingleOutputStreamOperator.keyBy(0).sum(1);

        sum.print();

        try {
            executionEnvironment.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

